import { memo, useCallback, useRef, useState } from "react"
import { BaseContiner, TableContainer, TableHeader } from "../../../csscomponents/base"
import { Button, Col, Flex, Form, Input, Modal, Row, Space, Table } from "antd";
import {
    PlusOutlined
} from '@ant-design/icons';
import { useForm } from "antd/es/form/Form";
import { ErrorBox } from "../../../components/error-box";
import { IFormRef } from "../../../types";
import { ILawsType, ILawsTypeSearchParams, useDeletedlawsType, useGetLawsType } from "../../../service/laws-type-service";
import LawsTypeForm from "./laws-type-form";

export const LawTypePage = () => {

    const defaultQueryParams: ILawsTypeSearchParams = {
        lawsTypeName: "",
        page: 1,
        limit: 10
    }
    const [queryForm] = useForm();
    const [open, setOpen] = useState<boolean>(false);
    const [update, setUpdate] = useState<ILawsType>();
    const FormRef = useRef<IFormRef>();
    const openFn = useCallback((open: boolean) => {
        setOpen(open)
    }, [])
    /**
     * 搜索参数
     */
    const [queryParams, setQueryParams] = useState<ILawsTypeSearchParams>(defaultQueryParams)

    /**
     * 搜索角色列表Handler
     * @param values 搜索参数
     */
    const onFinish = (values: { lawsTypeName: string }) => {
        setQueryParams({
            ...queryParams,
            lawsTypeName: values.lawsTypeName,
            page: 1,
            limit: 10
        })
    }
    /**
     * 重置方法
     */
    const resetQueryParams = () => {
        queryForm.resetFields();
        setQueryParams(defaultQueryParams);
    }


    /**删除角色 */
    const removeHandler = (lawsTypeId: number) => {
        Modal.confirm({
            title: '⚠️警告',
            content: '你确认执行改操作吗?',
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {
                await deleteMutation({ lawsTypeId });
                refetch();
            },
        });
    };

    /**
     * !获取法律分类列表Hook
     */
    const { isLoading, isError, data: dataSource, error, refetch } = useGetLawsType(queryParams);

    /**
     * !删除法律分类HOOK
     */
    const { mutateAsync: deleteMutation, isLoading: DIsLoading } = useDeletedlawsType();
    /**
     * 分页配置
     */
    const paginationProps = {
        total: dataSource?.count,
        pageSize: queryParams.limit,
        current: queryParams.page,
        showTotal: (count: number) => {
            return `共 ${count} 条`;
        },
        onChange: (pageNum: number) => {
            setQueryParams({ ...queryParams, page: pageNum });
        },
    };
    const columns = [
        {
            title: '类型ID',
            dataIndex: 'lawsTypeId',
            key: 'lawsTypeId',
        },
        {
            title: '法律分类名称',
            dataIndex: 'lawsTypeName',
            key: 'lawsTypeName',
        },
        {
            title: '更多操作',
            render(project: ILawsType) {
                return (
                    <div>
                        <Button
                            style={{ marginRight: '1.2rem' }}
                            onClick={() => {
                                setUpdate(project);
                                setOpen(true);
                            }}
                        >
                            修改
                        </Button>
                        <Button
                            loading={DIsLoading}
                            danger
                            onClick={() => removeHandler(project.lawsTypeId)}
                        >
                            删除
                        </Button>
                    </div>
                );
            },
        },
    ];
    return <BaseContiner>
        <TableHeader>
            <Form
                form={queryForm}
                style={{ width: '100%' }}
                onFinish={onFinish}
                autoComplete="off"
            >
                <Row gutter={16}>
                    <Col span={10}>
                        <Form.Item label="法律分类" name="lawsTypeName" >
                            <Input />
                        </Form.Item>
                    </Col>
                    <Col span={10}>
                        <Form.Item >
                            <Space>
                                <Button type="primary" htmlType="submit">
                                    搜索
                                </Button>
                                <Button type="primary" onClick={() => resetQueryParams()}>
                                    重置
                                </Button>
                            </Space>
                        </Form.Item>
                    </Col>
                    <Col span={4}>
                        <Flex gap="small" justify="flex-end">
                            <Button type="primary" icon={<PlusOutlined />} onClick={() => {
                                if (FormRef.current?.reset) {
                                    FormRef.current?.reset();
                                }
                                setUpdate(undefined)
                                setOpen(true);
                            }}>
                                添加
                            </Button>
                        </Flex>
                    </Col>
                </Row>
            </Form>
        </TableHeader>
        <TableContainer>
            {isError ? (
                <ErrorBox error={error as { message: string }} />
            ) : (
                <Table
                    rowSelection={{ type: 'checkbox' }}
                    pagination={paginationProps}
                    dataSource={dataSource?.list}
                    columns={columns}
                    loading={isLoading}
                    rowKey={(row) => row?.lawsTypeId}
                />
            )}
        </TableContainer>
        <LawsTypeForm open={open} onRef={FormRef} openFn={openFn} refetch={refetch} update={update} />
    </BaseContiner>
}

export default memo(LawTypePage)